﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using System.Reflection;

namespace Catalyst.Web.DynamicData
{
    /// <summary>
    ///  A parameter responsible for creating a LambdaExpression that compares the value to null or if a String performs String.IsNullOrEmpty().
    /// </summary>
    public class NotNullOrEmptyParameter : DynamicExpressionParameterBase
    {
        public override System.Linq.Expressions.LambdaExpression GetLambdaExpression(Type itType)
        {
            if (this.Type == TypeCode.String)
                return GetStringLambdaExpression(itType);
            else
            {
                return DynamicExpression.ParseLambda(itType, typeof(bool), string.Format("{0} != null", this.Name), "");
            }
        }

        private LambdaExpression GetStringLambdaExpression(Type itType)
        {
            ParameterExpression parameterExpression = Expression.Parameter(itType, "");
            return Expression.Lambda
                (
                    Expression.AndAlso
                    (
                        Expression.NotEqual
                        (
                            Expression.Constant(null),
                            parameterExpression
                        ),
                        Expression.NotEqual
                        (
                            Expression.Property
                            (
                                Expression.Property
                                (
                                    parameterExpression,
                                    this.Name
                                ),
                                "Length"
                            ),
                            Expression.Constant(0)
                        )
                    )
                    ,
                    new ParameterExpression[] { parameterExpression }
                );
        }
    }
}
